package com.cg.asm.core.config.loading;

import com.cg.asm.core.config.loading.cache.auth.IAuthApi;
import com.cg.asm.license.holder.LicenseVerifyHolder;
import com.cg.asm.license.verify.LicenseVerify;
import com.cg.asm.client.AsmFileUtils;
import com.cg.asm.client.exception.AsmException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component
public class StartupLoading implements CommandLineRunner {

    private IAuthApi authApi;
    public static InputStream licenseInputStream;

    @Autowired
    public StartupLoading(IAuthApi authApi) {
        this.authApi = authApi;
    }

    @Override
    public void run(String... strings) {
        try {
            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            StartupLoading.licenseInputStream = resolver.getResource("/" + LicenseVerify.getConfiPath()).getInputStream();
            LicenseVerify lv = LicenseVerifyHolder.getLicenseVerify(StartupLoading.licenseInputStream);
            InputStream licStream = resolver.getResource("/" + lv.getLicName()).getInputStream();
            File licFile = AsmFileUtils.InputStreamToFile(licStream, "license", ".lic");
            if (null != licFile) {
                if (!"success".equals(lv.uninstall())
                        || !"success".equals(lv.install(licFile))
                        || !"success".equals(lv.verify())) {
                    throw new AsmException("无效的授权文件");
                } else {
                    authApi.initAuth();
                }
            } else {
                throw new AsmException("未找到授权文件");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
